package com.yantong.security;


import com.yantong.config.ApplicationContextRegister;
import com.yantong.constant.BusinessCode;
import com.yantong.constant.CentreStatus;
import com.yantong.constant.UserStatus;
import com.yantong.exception.BDException;
import com.yantong.pojo.Centre;
import com.yantong.service.CentreService;
import com.yantong.service.MenuService;
import com.yantong.service.UserService;
import com.yantong.utils.ShiroUtils;
import com.yantong.utils.SysUser;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import java.util.*;

/**
 * @author kanghaixin
 */
public class UserRealm extends AuthorizingRealm {

	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection arg0) {
		Long userId = ShiroUtils.getUserId();
		MenuService menuService = ApplicationContextRegister.getBean(MenuService.class);
		Set<String> perms = menuService.getPermsByUserId(userId);
		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
		info.setStringPermissions(perms);
		return info;
	}

	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		String username = (String) token.getPrincipal();
		Map<String, Object> map = new HashMap<>(2);
		map.put("name", username);
		map.put("status", "1");
		String password = new String((char[]) token.getCredentials());

		UserService userService = ApplicationContextRegister.getBean(UserService.class);
		// 查询用户信息
		List<SysUser> list = userService.getUserList(map);
		if (CollectionUtils.isEmpty(list)) {
			throw new UnknownAccountException(BusinessCode.ACCOUNT_OR_PSW_ERROR.getMsg());
		}
		SysUser user = list.get(0);
		// 账号不存在
		if (user == null) {
			throw new UnknownAccountException(BusinessCode.ACCOUNT_OR_PSW_ERROR.getMsg());
		}

		if (user.getCentreId() != null) {
			CentreService centreService = ApplicationContextRegister.getBean(CentreService.class);
			Centre centre = centreService.getByKey(user.getCentreId());
			if (centre == null || CentreStatus.OFF.equals(centre.getStatus())) {
				throw new BDException(BusinessCode.USER_CENTRE_ERROR.getMsg());
			}
		}
		// 密码错误
		if (!password.equals(user.getPassword())) {
			throw new IncorrectCredentialsException(BusinessCode.ACCOUNT_OR_PSW_ERROR.getMsg());
		}

		// 账号锁定
		if (Objects.equals(UserStatus.user_disable, user.getStatus())) {
			throw new LockedAccountException(BusinessCode.ACCOUNT_LOCKED_ERROR.getMsg());
		}
		return new SimpleAuthenticationInfo(user, password, getName());
	}
}
